package com.vastcom.tools;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.StringTokenizer;
import java.util.UUID;

import org.aspectj.weaver.patterns.ThisOrTargetAnnotationPointcut;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.joda.time.Instant;

//工具类
/**
 * @author jin
 *
 */
public class Tools {
	private static int  BUFFER_SIZE=1024;
	/**
	 * 生成32个字符长度的UUID
	 * 
	 * @author aJie
	 * @return String
	 */
	public static String newUUID() {
		String uuid = UUID.randomUUID().toString();
		uuid = uuid.replace("-", "");
		return uuid;
	}

	/**
	 * 验证字符串是否为null和"",满足返回true，不满足返回false
	 * 
	 * @author aJie
	 * @param str
	 * @return boolean
	 */
	public static boolean isNullOrSpace(String str) {
		return null == str || "".equals(str) ? true : false;
	}

	/**
	 * 得到配置文件中的上传文件存储的路径
	 * 
	 * @author ajie
	 * @return
	 */
	public static String getUplaodDir(String classfier) {
		String dir = "";
		SAXReader reader = new SAXReader();
		Document document = null;
		try {
			InputStream in = Tools.class.getClassLoader().getResourceAsStream("FileSaveConfig.xml");
			document = reader.read(in);
			Element root = document.getRootElement();
			Element key = root.element(classfier);
			key = key.element("param");
			Attribute attr = key.attribute("value");
			dir = attr.getValue();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dir;
	}

	/**
	 * 得到配置文件中的下载文件的路径
	 * 
	 * @author ajie
	 * @return
	 */
	public static String getDownloadDir() {
		String dir = "";
		SAXReader reader = new SAXReader();
		Document document = null;
		try {
			InputStream in = Tools.class.getClassLoader().getResourceAsStream("JSTConfig.xml");
			document = reader.read(in);
			Element root = document.getRootElement();
			Element key = root.element("download");
			key = key.element("param");
			Attribute attr = key.attribute("value");
			dir = attr.getValue();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dir;
	}

	/***
	 * 得到配置文件中的下载文件的路径
	 * @author lulu
	 * @param filelocation JSTConfig.xml 节点名
	 * @return 返回 JSTConfig.xml filelocation 配置的路径
	 */
	public static String getFilesLocation(String filelocation) {
		String dir = "";
		SAXReader reader = new SAXReader();
		Document document = null;
		try {
			//InputStream in = Tools.class.getClassLoader().getResourceAsStream("FileSaveConfig.xml");
			InputStream in = Tools.class.getClassLoader().getResourceAsStream("JZConfig.xml");
			document = reader.read(in);
			Element root = document.getRootElement();
			Element key = root.element(filelocation);
			key = key.element("param");
			Attribute attr = key.attribute("value");
			dir = attr.getValue();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dir;
	}
	
	
	
	/**
	 * 按格式取当前时间
	 * 
	 * @param format
	 *            日期格式,如"yyyy-MM-dd HH:mm:ss" 、"yyyy-MM-dd HH:mm"等
	 * @author ajie
	 * @return
	 */
	public static String getTimeNow(String format) {
		try {
			Date d = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			return sdf.format(d);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * 得到前几天的日期
	 * 
	 * @param todayDate
	 *            指定日期
	 * @param days
	 *            天数
	 * @author ajie
	 * @return
	 */
	public static String getPreDaysDate(String todayDate, int days) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date date = sdf.parse(todayDate);
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			cal.add(Calendar.DAY_OF_MONTH, -days);
			return sdf.format(cal.getTime());
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * 得到后几天的日期
	 * 
	 * @param todayDate
	 *            指定日期
	 * @param days
	 *            天数
	 * @author ajie
	 * @return
	 */
	public static String getNextDaysDate(String todayDate, int days) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date date = sdf.parse(todayDate);
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			cal.add(Calendar.DAY_OF_MONTH, days);
			return sdf.format(cal.getTime());
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * 比较时间data1是否在时间data2之前
	 * 
	 * @param data1
	 * @param date2
	 * @param format
	 *            日期格式,如"yyyy-MM-dd HH:mm:ss" 、"yyyy-MM-dd HH:mm"等
	 * @author ajie
	 * @return
	 */
	public static boolean isDateBefore(String data1, String date2, String format) {
		java.text.DateFormat df = new SimpleDateFormat(format);
		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();
		try {
			c1.setTime(df.parse(data1));
			c2.setTime(df.parse(date2));
		} catch (Exception e) {
			e.printStackTrace();
		}
		int result = c1.compareTo(c2);
		if (result <= 0)
			return true;
		else
			return false;
	}

	/**
	 * 将字符串转成日期格式
	 * 
	 * @param strDate
	 * @param format
	 *            日期格式,如"yyyy-MM-dd HH:mm:ss" 、"yyyy-MM-dd HH:mm"等
	 * @author ajie
	 * @return
	 */
	public static Date convertToDate(String strDate, String format) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			Date date = sdf.parse(strDate);
			return date;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static String convertDateToString(String format,Date date){
		DateFormat format1 = new SimpleDateFormat(format);
		return format1.format(date);
	}
	
	/**
	 * long转date
	 * 
	 * @param long
	 * @return datatime
	 */
	public static String long2Date(long lSysTime1 ){
		SimpleDateFormat sdf= new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
		//前面的lSysTime是秒数，先乘1000得到毫秒数，再转为java.util.Date类型
		java.util.Date dt = new Date(lSysTime1 * 1000);  
		String sDateTime = sdf.format(dt);  //得到精确到秒的表示：08/31/2006 21:08:00
		return sDateTime;
	}
	
	public static long covertTimeStampToLong(String currentdate){
	/*	long n;
		try {
			SimpleDateFormat d= new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date d1=d.parse(currentdate);
			n =d1.parse(currentdate);
			
			return n;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return 0;
		}*/
		//long epoch = new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm:ss").parse("01/01/1970 01:00:00");
		long x;
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date d = sdf.parse(currentdate);
			
			Timestamp appointTime=Timestamp.valueOf(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(d));
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
									Date date = df.parse(String.valueOf(appointTime));
									long s=date.getTime();
					String unixDate=String.valueOf(s).substring(0, 10);
					x=Long.parseLong(unixDate);
					return x;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return 0;
		}
	}
	
	public static String covertLontToDateString(long date){
		String dateString=new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date(date * 1000));
	return dateString;
	}
	

	

	/**
	 * 得到文件的扩展名
	 * 
	 * @param fileName
	 * @author ajie
	 * @return
	 */
	public static String getExtention(String fileName) {
		String kzm = "";
		try {
			int pos = fileName.lastIndexOf(".");
			kzm = (fileName.substring(pos)).toLowerCase();// 将其获得的后缀名都小写
		} catch (Exception e) {
			e.printStackTrace();
		}
		return kzm;
	}
	
	public static boolean allowFileOper(String filetype, String allowtype) {
		String[] at = allowtype.split(",");
		// 1:jpg , 2: png ,3:gif , 4:doc , 5:docx ,6:xls, 7:xlsx ,8:pdf , 9:zip
		if (".jpg".equals(filetype)) {
			filetype = "1";
		} else if (".png".equals(filetype)) {
			filetype = "2";
		} else if (".gif".equals(filetype)) {
			filetype = "3";
		} else if (".doc".equals(filetype)) {
			filetype = "4";
		} else if (".docx".equals(filetype)) {
			filetype = "5";
		} else if (".xls".equals(filetype)) {
			filetype = "6";
		} else if (".xlsx".equals(filetype)) {
			filetype = "7";
		} else if (".pdf".equals(filetype)) {
			filetype = "8";
		} else if (".zip".equals(filetype)) {
			filetype = "9";
		}
		 else if (".ftl".equals(filetype)) {
				filetype = "10";
			}
		for (int n = 0, len = at.length; n < len; n++) {
			if (at[n].equals(filetype)) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 得到流水号
	 * 
	 * @param 
	 * @author ajie
	 * @return
	 */
	 public static String getMaxId(String firstno){  
        //培训报名开始编号001
		 
		 SimpleDateFormat format= new SimpleDateFormat("yyyyMMddHHmmss");  
         String date=format.format(new Date());  
         String firstNo=firstno;  
         int t = (int) Math.floor(100*Math.random()) + 1; 
         String lastNo=firstNo+date+t;
        		 
                    /** 
          * 此处可以冲数据库中查询然后进行比较，如果为空默认为lastno如果部位空 
          * 讲取出的流水号作为temp，然后截取，累加返回。 
          */  
         StringBuffer sb=new StringBuffer();  
         String temp=lastNo.substring(lastNo.length()-3, lastNo.length());  
       
         if(Integer.parseInt(temp)>=1&&Integer.parseInt(temp)<999){  
             temp=String.valueOf(Integer.parseInt(temp)+1);  
         }  
         switch (temp.length()) {  
         case 1:  
             temp="00"+temp;  
             break;  
         case 2:  
             temp="0"+temp;  
             break;  
         default:  
             break;  
         }  
         lastNo=firstNo+date+temp;  
     return lastNo;  
       
 }  
	

	
	//得到考试准考证号
	 public static String getZkzh(String ksrq,String maxId){
 //培训报名开始编号001
		 
		 
        String firstNo=ksrq .replace("-", "");
         //int t = (int) Math.floor(100*Math.random()) + 1; 
       
        int t=(Integer.parseInt(maxId))+1;
       // System.out.println("MaxId"+maxId+"t   "+t);     
        String maxid=String.valueOf(t);
        switch (maxid.length()) {  
      case 1:  
          maxid="00"+maxid;  
          break;  
      case 2:  
          maxid="0"+maxid;  
          break;  
      default:  
          break;  
      }  
        String lastNo=firstNo.trim()+maxid;
        	//	 String lastNo=firstNo;
        		 
                    /** 
//          * 此处可以冲数据库中查询然后进行比较，如果为空默认为lastno如果部位空 
//          * 讲取出的流水号作为temp，然后截取，累加返回。 
//          */  
//         StringBuffer sb=new StringBuffer();  
//         String temp=lastNo.substring(lastNo.length()-3, lastNo.length());  
//       
//         if(Integer.parseInt(temp)>=1&&Integer.parseInt(temp)<999){  
//             temp=String.valueOf(Integer.parseInt(temp)+1);  
//         }  
//         switch (temp.length()) {  
//         case 1:  
//             temp="00"+temp;  
//             break;  
//         case 2:  
//             temp="0"+temp;  
//             break;  
//         default:  
//             break;  
//         }  
//         lastNo=firstNo+date+temp;  
   return lastNo;  
		// return null;
	 }
	 
	public String ConvertToTimestampString(Date d){
		int[] ymdhms=new int[6];
		ymdhms[0]=d.getYear();
		ymdhms[1]=d.getMonth();
		ymdhms[2]=d.getDay();
		ymdhms[3]=d.getHours();
		ymdhms[4]=d.getMinutes();
		ymdhms[5]=d.getSeconds();
		StringBuffer sb=new StringBuffer();
		sb.append(1900+ymdhms[0]);
		if (ymdhms[1]<10){
			sb.append("-0"+ymdhms[1]);
		}else{
			sb.append("-"+ymdhms[1]);
		}
		if (ymdhms[2]<10){
			sb.append("-0"+ymdhms[2]);
		}else{
			sb.append("-"+ymdhms[2]);
		}
		sb.append(" ");
		if (ymdhms[3]<10){
			sb.append("0"+ymdhms[3]);
		}else{
			sb.append(ymdhms[3]);
		}
		if (ymdhms[4]<10){
			sb.append(":0"+ymdhms[4]);
		}else{
			sb.append(":"+ymdhms[4]);
		}
		if (ymdhms[5]<10){
			sb.append(":0"+ymdhms[5]);
		}else{
			sb.append(":"+ymdhms[5]);
		}
		return sb.toString();
	}
	
	/**
	 * 转换get后面得的首字母为大写
	 * 
	 * @param fildeName
	 * @return
	 * @throws Exception
	 */
	public static String getMethodName(String fildeName) throws Exception {
		byte[] items = fildeName.getBytes();
		items[0] = (byte) ((char) items[0] - 'a' + 'A');
		return new String(items);
	}
	
	
	
	/**
	 * 将Date转化为Timestamp(Oracle常用)
	 * 
	 * @param
	 * @author ljdd
	 * @return
	 */
	public static Timestamp DatetoTimestamp(Date date) {
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String datestr;
		datestr = format.format(date);
		return Timestamp.valueOf(datestr);
	}
	
	
	
	/***
	 * 删除JSTConfig.xml 中 path 项中叫filename 的文件
	 * @param path
	 * @param filename
	 * @return 成功true ,失败 false
	 */
	public static boolean delFile(String path,String filename){
		try{
			String desFile = Tools.getFilesLocation(path)+filename;
			File f=new File(desFile);
			if (f.exists()){
				f.delete();
				return true;
			}
			return false;
		}catch(Exception ex){
			return false;
		}
	}
	
	public static boolean delFileByPath(String filename){
		try{
			String desFile = filename;
			File f=new File(desFile);
			if (f.exists()){
				f.delete();
				return true;
			}
			return false;
		}catch(Exception ex){
			return false;
		}
	}
	
	/***
	 * 保存叫filename 的文件到 JSTConfig.xml 中 path 项对应的文件中
	 * @param path
	 * @param filename
	 * @return 成功true ,失败 false
	 */
	public static boolean Saveile(File file,String classfier,String filename){
		try {
			String path=getUplaodDir(classfier);
				String desFile = path+filename;
				File writeFile = new File(desFile);
//				if (!writeFile.exists()) {
					InputStream in = null;
					OutputStream out = null;
					in = new BufferedInputStream(new FileInputStream(
							file), BUFFER_SIZE);
					out = new BufferedOutputStream(new FileOutputStream(
							writeFile), BUFFER_SIZE);
					byte[] buffer = new byte[BUFFER_SIZE];
					int l=0;
					while ((l=in.read(buffer)) > 0) {
						out.write(buffer,0,l);
					}
					if (null != in) {
						in.close();
					}
					if (null != out) {
						out.close();
					}
					return true;
//				} else {
//					return false;
//				}
		} catch (Exception ex) {
			ex.printStackTrace();
			return false;
		}
	}
	
	
	public static File saveFile(File file,String classfier,String filename){
		try {
			String path=getUplaodDir(classfier);
				String desFile = path+filename;
				File writeFile = new File(desFile);
//				if (!writeFile.exists()) {
					InputStream in = null;
					OutputStream out = null;
					in = new BufferedInputStream(new FileInputStream(
							file), BUFFER_SIZE);
					out = new BufferedOutputStream(new FileOutputStream(
							writeFile), BUFFER_SIZE);
					byte[] buffer = new byte[BUFFER_SIZE];
					int l=0;
					while ((l=in.read(buffer)) > 0) {
						out.write(buffer,0,l);
					}
					if (null != in) {
						in.close();
					}
					if (null != out) {
						out.close();
					}
					return writeFile;
//				} else {
//					return false;
//				}
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}
	/***
	 * 获取JSTConfig.xml 中 path 项中叫filename 的文件
	 * @param classfier 分类
	 * @param filename
	 * @return 文件流
	 */
	public static InputStream getDownloadFile(String classfier,String filename)  {
		String desFile = Tools.getFilesLocation(classfier)+filename;
		try {
			return new FileInputStream(desFile);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	// 删除文件夹  
    // param folderPath 文件夹完整绝对路径  
    public static void delFolder(String folderPath) {  
        try {  
            delAllFile(folderPath); // 删除完里面所有内容  
            String filePath = folderPath;  
            filePath = filePath.toString();  
            java.io.File myFilePath = new java.io.File(filePath);  
            myFilePath.delete(); // 删除空文件夹  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
  
    // 删除指定文件夹下所有文件  
    // param path 文件夹完整绝对路径  
    public static boolean delAllFile(String path) {  
        boolean flag = false;  
        File file = new File(path);  
        if (!file.exists()) {  
            return flag;  
        }  
        if (!file.isDirectory()) {  
            return flag;  
        }  
        String[] tempList = file.list();  
        File temp = null;  
        for (int i = 0; i < tempList.length; i++) {  
            if (path.endsWith(File.separator)) {  
                temp = new File(path + tempList[i]);  
            } else {  
                temp = new File(path + File.separator + tempList[i]);  
            }  
            if (temp.isFile()) {  
                temp.delete();  
            }  
            if (temp.isDirectory()) {  
                delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件  
                delFolder(path + "/" + tempList[i]);// 再删除空文件夹  
                flag = true;  
            }  
        }  
        return flag;  
    }  
    
    
    
    /** 
     * 新建目录 
     */  
    public static boolean newDir(String path) throws Exception {  
        File file = new File(path);  
        return file.mkdirs();//创建目录  
    }  
      
    /** 
     * 删除目录 
     */  
    public static boolean deleteDir(String path) throws Exception {  
        File file = new File(path);  
        if (!file.exists())  
            return false;// 目录不存在退出  
        if (file.isFile()) // 如果是文件删除  
        {  
            file.delete();  
            return false;  
        }  
        File[] files = file.listFiles();// 如果目录中有文件递归删除文件  
        for (int i = 0; i < files.length; i++) {  
            deleteDir(files[i].getAbsolutePath());  
        }  
        file.delete();  
          
        return file.delete();//删除目录  
    }  
  
    /** 
     * 更新目录 
     */  
    public static boolean updateDir(String path, String newPath) throws Exception {  
        File file = new File(path);  
        File newFile = new File(newPath);  
        return file.renameTo(newFile);  
    }  
    
    
    public static String getFileSuffix(String fileName) throws Exception {  
        return fileName.substring(fileName.lastIndexOf(".") + 1,  
                fileName.length()).toUpperCase();  
    }  
  
    /** 
     * 创建多级目录 
     *  
     * @param path 
     *            目录的绝对路径 
     */  
    public static void createMultilevelDir(String path) {  
        try {  
            StringTokenizer st = new StringTokenizer(path, "/");  
            String path1 = st.nextToken() + "/";  
            String path2 = path1;  
            while (st.hasMoreTokens()) {  
  
                path1 = st.nextToken() + "/";  
                path2 += path1;  
                File inbox = new File(path2);  
                if (!inbox.exists())  
                    inbox.mkdir();  
  
            }  
        } catch (Exception e) {  
            System.out.println("目录创建失败" + e);  
            e.printStackTrace();  
        }  
  
    }  
  
    /** 
     * 删除文件/目录(递归删除文件/目录) 
     *  
     * @param path 
     *            文件或文件夹的绝对路径 
     */  
    public static void deleteAll(String dirpath) {  
        if (dirpath == null) {  
            System.out.println("目录为空");  
        } else {  
            File path = new File(dirpath);  
            try {  
                if (!path.exists())  
                    return;// 目录不存在退出  
                if (path.isFile()) // 如果是文件删除  
                {  
                    path.delete();  
                    return;  
                }  
                File[] files = path.listFiles();// 如果目录中有文件递归删除文件  
                for (int i = 0; i < files.length; i++) {  
                    deleteAll(files[i].getAbsolutePath());  
                }  
                path.delete();  
  
            } catch (Exception e) {  
                System.out.println("文件/目录 删除失败" + e);  
                e.printStackTrace();  
            }  
        }  
    }  
  
    /** 
     * 文件/目录 重命名 
     *  
     * @param oldPath 
     *            原有路径（绝对路径） 
     * @param newPath 
     *            更新路径 
     * @author lyf 注：不能修改上层次的目录 
     */  
    public static void renameDir(String oldPath, String newPath) {  
        File oldFile = new File(oldPath);// 文件或目录  
        File newFile = new File(newPath);// 文件或目录  
        try {  
            boolean success = oldFile.renameTo(newFile);// 重命名  
            if (!success) {  
                System.out.println("重命名失败");  
            } else {  
                System.out.println("重命名成功");  
            }  
        } catch (RuntimeException e) {  
            e.printStackTrace();  
        }  
  
    } 
    
    
    /** 
     *  
     * 功能描述：创建目录 
     * @param descDirName  目录名,包含路径 
     * @return             返回： 
     *                          如果创建成功，则返回true，否则返回false 
     */  
    public static boolean createDirectory(String descDirName)  
    {  
        if(!descDirName.endsWith(File.separator))  
        {  
            descDirName = descDirName + File.separator;  
        }  
        File descDir = new File(descDirName);  
        if(descDir.exists())  
        {  
            System.out.println("目录" + descDirName + "已存在!");  
            return false;  
        }  	
        //创建目录  
        if(descDir.mkdirs())  
        {  
            System.out.println("目录" + descDirName + "创建成功!");  
            return true;  
        }  
        else  
        {  
            System.out.println("目录" + descDirName + "创建失败!");  
            return false;  
        }  
          
    }  
    
    public static void copyFile(String oldPath, String newPath) {  
        try {  
            int bytesum = 0;  
            int byteread = 0;  
            File oldfile = new File(oldPath);  
            if (oldfile.exists()) { // 文件存在时  
                InputStream inStream = new FileInputStream(oldPath); // 读入原文件  
                FileOutputStream fs = new FileOutputStream(newPath);  
                byte[] buffer = new byte[1444];  
                while ((byteread = inStream.read(buffer)) != -1) {  
                    bytesum += byteread; // 字节数 文件大小  
                    System.out.println(bytesum);  
                    fs.write(buffer, 0, byteread);  
                }  
                inStream.close();  
                 
            }  
        } catch (Exception e) {  
            System.out.println("复制单个文件操作出错 ");  
            e.printStackTrace();  
        }  
    }  
    
    public static void copyFolder(String oldPath, String newPath) {  
        try {  
            (new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹  
            File a = new File(oldPath);  
            String[] file = a.list();  
            File temp = null;  
            for (int i = 0; i < file.length; i++) {  
                if (oldPath.endsWith(File.separator)) {  
                    temp = new File(oldPath + file[i]);  
                } else {  
                    temp = new File(oldPath + File.separator + file[i]);  
                }  
                if (temp.isFile()) {  
                    FileInputStream input = new FileInputStream(temp);  
                    FileOutputStream output = new FileOutputStream(newPath  
                            + "/" + (temp.getName()).toString());  
                    byte[] b = new byte[1024 * 5];  
                    int len;  
                    while ((len = input.read(b)) != -1) {  
                        output.write(b, 0, len);  
                    }  
                    output.flush();  
                    output.close();  
                    input.close();  
                     
                }  
                if (temp.isDirectory()) {// 如果是子文件夹  
                    copyFolder(oldPath + "/" + file[i], newPath + "/"  
                            + file[i]);  
                }  
            }  
        } catch (Exception e) {  
            System.out.println("复制整个文件夹内容操作出错 ");  
            e.printStackTrace();  
        }  
    }  
    
    public static String covertToCronExpression(Timestamp ts){
    	//dataString="2015-03-28 15:37:10";
    	String tmp;  
    	
    	//SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    	//Timestamp ts = new Timestamp(System.currentTimeMillis());  
    	      Date d = new Date();  
    	       try {  
    	           d = ts;  
    	           System.out.println(d);  
    	       } catch (Exception e) {  
    	           e.printStackTrace();  
    	       }  


//    	//Date d=null;
//		try {
//			d = df.parse(dataString);
//		} catch (ParseException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
   	
    	Calendar cal = Calendar.getInstance();
    	cal.setTime(d);
    	int year = cal.get(Calendar.YEAR);
    	int month=1;
    	month+= cal.get(Calendar.MONTH);
    	int date = cal.get(Calendar.DATE);
    	int hour = cal.get(Calendar.HOUR_OF_DAY);
    	int minute = cal.get(Calendar.MINUTE);
    	
         tmp="0 "+String.valueOf(minute)+" "+String.valueOf(hour)+" "+String.valueOf(date)+
        		 " "+String.valueOf(month)+" ? "+String.valueOf(year) ;

        
    	//0 17 18 23 3 ? 2015
    	
    	return tmp;
    }
    
    
    
    public static void CopyFiles_Help( String src, 
    		 String dest) 
    {
    	int nIndex = dest.lastIndexOf(File.separator);
    	CreateFolders(dest.substring(0, nIndex));
    	CopyFile(src, dest);
    }
    
    public static  void CreateFolders( String folders) {    

        StringTokenizer st = new StringTokenizer(folders, File.separator);        
    	StringBuilder sb = new StringBuilder();         
    	String osname = System.getProperty("os.name");  
    	if (osname.compareToIgnoreCase("linux") == 0)  
    	sb.append(File.separator);   
    	while (st.hasMoreTokens()) {   
    	sb.append(st.nextToken());    
    	File file = new File(sb.toString());  
    	if (!file.exists())  
    	file.mkdir();   
    	sb.append(File.separator);   
    	}
    }
    
    
    
    public static  boolean CopyFile(final String src, final String dest) {  
    	        File srcFile = new File(src);  
    		        File destFile = new File(dest);  
    		        try {  
    		            if(!destFile.exists())  
                    destFile.createNewFile();  
    	              
    	            FileInputStream fin = new FileInputStream(srcFile);  
    		            FileOutputStream fout = new FileOutputStream(destFile);  
    		            int n = 0;  
    		            byte[] buf = new byte[4096];  
    		            while ( (n = fin.read(buf)) != -1 ) {  
    		                fout.write(buf, 0, n);  
    		            }  
    		              
    		            fout.close();  
    	            fin.close();  
    	  
    		        } catch (FileNotFoundException e) {  
    	            e.printStackTrace();  
    		            return false;  
    	        } catch (IOException e) {  
    	            e.printStackTrace();  
    		            return false;  
    		        }  
    	  
            return true;  
    		    }  
    		  
    		 
    /**
	 * 功能：保存文件。
	 * 
	 * @author 宋立君
	 * @date 2014年06月24日
	 * @param content
	 *      字节
	 * @param file
	 *      保存到的文件
	 * @throws IOException
	 */
	public static void save(byte[] content, File file) throws IOException {
		if (file == null) {
			throw new RuntimeException("保存文件不能为空");
		}
		if (content == null) {
			throw new RuntimeException("文件流不能为空");
		}
		InputStream is = new ByteArrayInputStream(content);
		save(is, file);
	}

	/**
	 * 功能：保存文件
	 * 
	 * @author 宋立君
	 * @date 2014年06月24日
	 * @param streamIn
	 *      文件流
	 * @param file
	 *      保存到的文件
	 * @throws IOException
	 */
	public static void save(InputStream streamIn, File file) throws IOException {
		if (file == null) {
			throw new RuntimeException("保存文件不能为空");
		}
		if (streamIn == null) {
			throw new RuntimeException("文件流不能为空");
		}
		// 输出流
		OutputStream streamOut = null;
		// 文件夹不存在就创建。
		if (!file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}
		streamOut = new FileOutputStream(file);
		int bytesRead = 0;
		byte[] buffer = new byte[8192];
		while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) {
			streamOut.write(buffer, 0, bytesRead);
		}
		streamOut.close();
		streamIn.close();
	}
    

  
}


